package com.shootforthestars;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;

import com.shootforthestars.objects.Rocket;
import com.shootforthestars.objects.RocketEffect;

public class Game extends BasicGame {
	private static final String GAME_TITLE = "ShootForTheStars";
	private Color backgroundColor;
	private World world;
	private boolean running;
	private float scrollOffset;

	public Game() {
		super(GAME_TITLE);
		backgroundColor = new Color(0x000033);
		running = true;
		scrollOffset = 0;
		world = new World();
	}

	@Override
	public void init(GameContainer container) throws SlickException {
		running = true;
		scrollOffset = 0;
		world.init();
		world.getRocket().applyEffect(new RocketEffect() {
			@Override
			public void applyToRocket(Rocket rocket) {
				rocket.giveBoost(10f);
			}
		});
	}

	@Override
	public void update(GameContainer container, int delta)
			throws SlickException {
		// Handle input
		Input input = container.getInput();
		if (input.isKeyPressed(Input.KEY_SPACE)) {
			running = (running == true) ? false : true;
		}

		// Do logic
		if (running == true) {
			// Update the level
			world.update(input, delta);

			// Center world around rocket
			Rocket rocket = world.getRocket();
			scrollOffset = rocket.getCollisionComponent().getShape()
					.getMaxY();

			// TODO handle game over
			if (world.isGameOver()) {
			} else if (world.isFinished()) {
			}
		}
	}

	@Override
	public void render(GameContainer container, Graphics graphics)
			throws SlickException {
		int containerWidth = container.getWidth();
		int containerHeight = container.getHeight();

		// Draw background color
		graphics.setColor(backgroundColor);
		graphics.fillRect(0, 0, containerWidth, containerHeight);

		// Begin relative drawing with scroll offset
		graphics.pushTransform();
		graphics.translate(0, -scrollOffset);

		// Set relative offset to center-bottom of screen
		graphics.translate(containerWidth / 2, containerHeight);

		// Draw level
		world.render(graphics);

		// End relative drawing
		graphics.popTransform();
	}

	public static void main(String[] arguments) {
		try {
			AppGameContainer app = new AppGameContainer(new Game());
			app.setShowFPS(false);
			app.setVerbose(false);
			app.setVSync(true);
			app.setUpdateOnlyWhenVisible(false);
			app.setAlwaysRender(true);
			app.setDisplayMode(800, 600, false);
			// app.setDisplayMode(1366, 768, true);
			app.start();
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}
}
